/******************************************************************************\
    HttpClient.h discribes a client class of http server.
    It's used with acm server. See main.cpp for details.
    Copyright (C) 2008  Victor Vinogradov (fly3333@gmail.com)

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
\******************************************************************************/

#pragma once 

#include <Common\BaseThread.h>
#include <map>
#include <string>
#include <vector>
#include <Common\StdFile.hpp>
#include <Common\Socket.hpp>
#include <Common\CriticalSection.hpp>
#include ".\HttpResponse.h"
#include ".\ContestantCookieDataBase.h"
#include <Common\Format.h>

class cWardHttpClient : public cBaseThread
{
private:
	cSocket Socket;
	//bool IsNeedToStop;
	cCriticalSection CriticalSection;
	unsigned long Key;
	static bool UrlDecode( std::string url, std::vector< std::string > &path, cFormat &parameter );
	static bool CookieDecode( const std::string &cookie, nsContestantCookieDataBase::sContestantCookieData &contestant_cookie_data );
protected:
	virtual unsigned long Process();
	cHttpResponse Get( const std::string &url, const std::map< std::string, std::string > &value );
	cHttpResponse Post( const std::string &url, const std::map< std::string, std::string > &value, const std::string &data );
public:
	cWardHttpClient( const cSocket &socket );
	~cWardHttpClient();
	friend class cHttpClient;
};

class cHttpClient : public cPointerObject< cWardHttpClient >
{
public:
	bool Create( const cSocket &socket )
	{
		cWardHttpClient *ward_http_client;
		try
		{
			ward_http_client = new cWardHttpClient( socket );			
		}
		catch( ... )
		{
			return false;
		}
		if( ward_http_client->Thread == INVALID_HANDLE_VALUE ||
			 ward_http_client->Thread.Resume() == -1 ||
			 !SwitchToWardObject( ward_http_client ) )
		{
			delete ward_http_client;
			return false;
		}
		return true;
	}
	void Destroy()
	{
		SwitchToSubObject( NULL );
	}
};
